package com.aspire.boc.mms.wmf.filter;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.aspire.boc.mms.wmf.log.OperLogger;
import com.aspire.boc.mms.wmf.model.WmfOperateLog;
import com.aspire.boc.mms.wmf.service.OperateLogService;
import com.aspire.boc.mms.wmf.util.AuthAnnotation;
import com.aspire.boc.mms.wmf.util.AuthAnnotation.NoAuth;
import com.aspire.boc.mms.wmf.util.SessionProvider;

import edu.yale.its.tp.cas.client.filter.CASFilter;

/**
 * 1.拦截器按照先后顺序进行拦截；
 * 
 * 2.拦截全部请求时使用"/**";
 * 
 * 3.拦截只针对
 * 
 * @author chenjianjun
 * @date 2013-4-18 上午11:59:58
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
	/**
	 * 
	 拦截器的前端，执行控制器之前所要处理的方法，通常用于权限控制、日志，其中，Object arg2表示下一个拦截器
	 */
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		
		HttpSession httpSession = request.getSession();
		Object securityUser = httpSession.getAttribute("securityUser");
		String servletPath = request.getServletPath();
		if(securityUser != null && "/login.do".equals(servletPath)) {
			response.sendRedirect("index.do"); // 返回提示页面
			return true;
		}
		return true;
	}

	/**
	 * 控制器的方法已经执行完毕，转换成视图之前的处理
	 */
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	/**
	 * 视图已处理完后执行的方法，通常用于释放资源；
	 */
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	private boolean checkAuth(HandlerMethod handlerMethod) {

		NoAuth noAuth = handlerMethod.getMethodAnnotation(AuthAnnotation.NoAuth.class);
		// 不需要验证直接继续
		return noAuth != null;
	}

	@SuppressWarnings("unchecked")
	private void logDB(HttpServletRequest request, HandlerMethod handlerMethod) {
		// 数据库日志
		try {
			WmfOperateLog cmOpera = new WmfOperateLog();
			Object username = request.getSession().getAttribute(
					CASFilter.CAS_FILTER_USER);
			cmOpera.setUsername(username == null ? "" : username.toString());
			cmOpera.setOperObject(request.getRequestURL().toString());
			MethodParameter[] parameters = handlerMethod.getMethodParameters();
			String pamsString = "";
			for (MethodParameter parameter : parameters) {
				//System.out.println(parameter.getParameterType());
				if (parameter.getParameterType() == javax.servlet.http.HttpServletRequest.class) {
					String parameterString = "{";
					Map<String, Object> map = request.getParameterMap();
					for (String key : map.keySet()) {
						String[] values = (String[]) map.get(key);
						parameterString = parameterString + key + "="
								+ values[0] + ",";
					}
//					Enumeration enumeration = request.getAttributeNames();
//					while(enumeration.hasMoreElements()){
//						Object object = enumeration.nextElement();
//						System.out.println("000000" + object);
//						System.out.println("000000" + request.getAttribute(object.toString()));
//					}
					if(parameterString.equals(",")){
						pamsString = pamsString.substring(0,pamsString.length() -1);
					}
					parameterString = parameterString + "}";
					cmOpera.setOperAction(parameterString);
				}
			}
			cmOpera.setSessionid(request.getSession().getId());
			operateLogService.insertOperateLog(cmOpera);
		} catch (Exception exception) {
			OperLogger.log(this,
					">>>>>>>>>>>>>>>>>>>>日志失效------------------------------",
					OperLogger.LOG_LEVEL.INFO);
			exception.printStackTrace();
		}
	}

	@Autowired
	private SessionProvider session;
	@Autowired
	private OperateLogService operateLogService;

}
